package com.xinghanlaser.applet.points;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.xinghanlaser.applet.base.flow.core.BasePoint;
import com.xinghanlaser.applet.entity.TopicBind;
import com.xinghanlaser.applet.entity.TopicHandleDetail;
import com.xinghanlaser.applet.service.ITopicBindService;
import com.xinghanlaser.applet.service.ITopicHandleDetailService;
import com.xinghanlaser.applet.service.ITopicHandleHistoryService;
import com.xinghanlaser.applet.service.ITopicService;
import com.xinghanlaser.applet.vo.point.ToFactoryMaintenanceVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

import static com.xinghanlaser.applet.constant.AdminConstant.*;


/**
 * <p>
 *
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/5/14 15:38
 */
@Component
public class ToFactoryMaintenancePoint extends BasePoint<ToFactoryMaintenanceVO> {
    @Resource
    private ITopicService topicService;

    @Resource
    private ITopicHandleDetailService handleService;

    @Resource
    private ITopicHandleHistoryService historyService;

    @Resource
    private ITopicBindService bindService;

    @Override
    @DSTransactional
    protected void pointOperation(ToFactoryMaintenanceVO vo) {
        final Long topicId = vo.getTopicId();

        // 校验申请单是否存在
        topicService.validatedTopicId(topicId);

        // 更新处理流程信息
        TopicHandleDetail handleEntity = topicService.getHandleEntityByTopicId(topicId);
        handleEntity.setCurrentPointId(getPointId());

        // 保存历史流程信息
        historyService.saveHistory(
                handleEntity.getId(),
                getPointId(),
                "已返厂维修",
                vo.getHandleNote()
        );

        handleService.updateById(handleEntity);

        // 绑定原厂维修人员
        this.bindTopic(topicId);
    }

    @Override
    protected Class<ToFactoryMaintenanceVO> getPointDataType() {
        return ToFactoryMaintenanceVO.class;
    }

    @Override
    public Long getPointId() {
        return 7L;
    }

    private void bindTopic(Long topicId){
        Set<TopicBind> insert = new HashSet<>();

        // 绑定所有维修人员
        insert.add(new TopicBind()
                .setTopicId(topicId)
                .setRoleId(MAINTENANCE_ROLE_ID)
        );

        // 绑定所有销售助理
        insert.add(new TopicBind()
                .setTopicId(topicId)
                .setRoleId(SALES_ROLE_ID)
        );

        bindService.saveBatch(insert);
    }
}
